<?php

/**
 * cpanel board management menu callback
 */
function cpanel_board_management($op = NULL) {
  global $user;
  $boards_per_page = 10;

  switch($op) {
    case 'get':
      CommonHelper::check_token('user_board');

      $query = db_select('user_term', 'ut')->extend('PagerDefault');
      $query->fields('ut', array('tid'))
        ->condition('ut.uid', $user->uid)
        ->orderBy('ut.tid', 'DESC');

      $data = array(
        'count' => $query->countQuery()->execute()->fetchField(),
        'boards' => array(),
      );

      $query->limit($boards_per_page);
      $tids = $query->execute()->fetchCol();

      $boards = taxonomy_term_load_multiple($tids);

      foreach($boards as $tid => $board) {
        $boards[$tid]->links_count = TaxonomyHelper::term_nodes_count($tid);
        $boards[$tid]->url = url("taxonomy/term/$tid");
        $data['boards'][] = $boards[$tid];
      }

      drupal_json_output($data);
      break;

    case 'delete':
      CommonHelper::check_token('user_board');

      $data = $_POST;

      if(empty($data)) {
        drupal_access_denied();
        drupal_exit();
      }

      foreach($data['boards_selected'] as $board) {
        taxonomy_term_delete($board['tid']);
      }

      drupal_json_output(NULL);
      break;

    default:
      LibraryHelper::load(array(
        array('name' => 'angular'),
        array('name' => 'angular-file-upload'),
        array('name' => 'angular-utils-pagination'),
      ));

      $category_options = list_allowed_values(field_info_field('field_category'));

      $user_board_token = drupal_get_token('user_board');
      drupal_add_js(array(
        'board_management' => array(
          'uid' => $user->uid,
          'boards_per_page' => $boards_per_page,
          'token' => $user_board_token,
          'category_options' => $category_options,
          'board' => (object) array(
              'tid' => '',
              'name' => '',
              'field_category' => (object) array(
                  'und' => array(
                    (object) array(
                      'value' => 'other'
                    )
                  )
                ),
              'field_privacy' => (object) array(
                  'und' => array(
                    (object) array(
                      'value' => 'public'
                    )
                  )
                ),
              'user_board_token' => $user_board_token,
            )
        )
      ), 'setting');

      drupal_add_js(drupal_get_path('module', 'helper') . '/js/crabii-validation-directive.js');

      $cpanel = drupal_get_path('module', 'cpanel');
      drupal_add_css($cpanel . '/css/board_management.css');
      drupal_add_js($cpanel . '/js/board_management.js');

      return array('#markup' => theme('cpanel_board_management'));
      break;
  }
}
